package com.chookss.home.logContacts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.LogUserEntity;
import com.chookss.home.entity.WeekEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.LogHurryDialog;
import com.chookss.view.listener.LogHurryDialogListener;
import com.chookss.view.WeekDialog;
import com.chookss.view.listener.WeekDialogListener;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.Nullable;

public class LogManagerCompleteActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.common_right_iv)
    ImageView commonRightIv;
    @BindView(R.id.llNoComplete)
    LinearLayout llNoComplete;
    @BindView(R.id.tvNoComplete)
    TextView tvNoComplete;
    @BindView(R.id.tvHurry)
    TextView tvHurry;
    @BindView(R.id.NoCompleteRv)
    RecyclerView completeNoRv;
    @BindView(R.id.tvComplete)
    TextView tvComplete;
    @BindView(R.id.completeRv)
    RecyclerView completeRv;
    @BindView(R.id.tvChaYue)
    TextView tvChaYue;
    @BindView(R.id.chaYueRv)
    RecyclerView chaYueRv;
    private MyContactEntityAdapter completeNoAdapter;
    private MyContactEntityAdapter completeAdapter;
    private MyContactEntityAdapter chaYueAdapter;
    private List<LogUserEntity> completeNoList = new ArrayList<>();
    private List<LogUserEntity> completeList = new ArrayList<>();
    private List<LogUserEntity> chaYueList = new ArrayList<>();
    private String teamCode = "", teamName = "", owerEmployeeCode = "";//团队code
    private String reportType = "3";
    private String currentTime = "";//选择时间
    private String currentOldTime = "";//当前时间
    private String reportName = "日志";
    private String dateInit = "本日";
    private int numRush = 0;//当前催一下
    private String currentDate = "";//当前日期  仅用来判断催一下所用
    private boolean timeEnd = true;//距离上一次催一下是否到一小时  true 超过1小时  false不到一小时
    private long oldTime = 0; //催一下

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_log_manager_complete);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        currentOldTime = getIntent().getStringExtra("currentTime");
        teamCode = getIntent().getStringExtra("teamCode");
        teamName = getIntent().getStringExtra("teamName");
        owerEmployeeCode = getIntent().getStringExtra("owerEmployeeCode");
        reportType = getIntent().getStringExtra("reportType");
        currentTime = currentOldTime;
        if ("1".equals(reportType)) {
            commonTitleTxt.setText(Utils.changeWeek(currentTime));
        } else {
            commonTitleTxt.setText(Utils.changeCnDate(currentTime));
        }
        if ("0".equals(reportType)) {
            reportName = "日报";
        } else if ("1".equals(reportType)) {
            reportName = "周报";
            getWeek();
        } else if ("2".equals(reportType)) {
            reportName = "月报";
        }
        try {
            mYear = Integer.parseInt(currentOldTime.substring(0, 4));
            if (currentOldTime.substring(5, 7).startsWith("0")) {
                mMonth = Integer.parseInt(currentOldTime.substring(6, 7)) - 1;
            } else {
                mMonth = Integer.parseInt(currentOldTime.substring(5, 7)) - 1;
            }
            if (reportType.equals("2")) {
                currentOldTime = currentOldTime.substring(0, 7);
                mDay = 28;
            } else {
                if (currentOldTime.substring(8, 10).startsWith("0")) {
                    mDay = Integer.parseInt(currentOldTime.substring(9, 10));
                } else {
                    mDay = Integer.parseInt(currentOldTime.substring(8, 10));
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }


        common_right_iv_ll.setVisibility(View.VISIBLE);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) commonRightIv.getLayoutParams();
        layoutParams.width = Utils.dip2px(this, 20);
        layoutParams.height = Utils.dip2px(this, 20);
        commonRightIv.setLayoutParams(layoutParams);
        commonRightIv.setBackgroundResource(R.drawable.icon_date_45);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 5);
        completeNoRv.setLayoutManager(gridLayoutManager1);
        completeNoAdapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, completeNoList);
        completeNoRv.setAdapter(completeNoAdapter);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(this, 5);
        completeRv.setLayoutManager(gridLayoutManager2);
        completeAdapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, completeList);
        completeRv.setAdapter(completeAdapter);
        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(this, 5);
        chaYueRv.setLayoutManager(gridLayoutManager3);
        chaYueAdapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, chaYueList);
        chaYueRv.setAdapter(chaYueAdapter);
        initDate();
        getData();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        currentDate = sf.format(c.getTime());
        String code = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        if (owerEmployeeCode.equals(code)) {
            tvHurry.setVisibility(View.VISIBLE);
            String cacheTeam = new ShareUtils().getString(this, teamCode, "");
            if (Utils.isNull(cacheTeam)) {
                tvHurry.setText("催一下(0/2)");
            } else {
                String[] cacheTeams = cacheTeam.split("_");
                if (cacheTeams.length > 2) {
                    String date = cacheTeams[0];
                    long time = System.currentTimeMillis() - Long.parseLong(cacheTeams[1]);
                    numRush = Utils.changeNumber(cacheTeams[2]);
                    if (currentDate.equals(date)) {
                        //还是当天
                        if (time < 1000 * 3600) {
                            timeEnd = false;
                        } else {
                            timeEnd = true;
                        }
                        tvHurry.setText("催一下(" + numRush + "/2)");
                    } else {
                        //第二天第一次调用接口
                        numRush = 0;
                        tvHurry.setText("催一下(0/2)");
                    }

                } else {
                    tvHurry.setText("催一下(0/2)");
                }
            }
        }
    }

    private void initDate() {
        if (tvComplete == null) {
            return;
        }
        if ("0".equals(reportType)) {
//           if(currentTime.equals(currentOldTime)){
//               dateInit="本日";
//           }else{
            dateInit = Utils.changeCnDate(currentTime);
//           }
        } else if ("1".equals(reportType)) {
//            if(currentTime.equals(currentOldTime)){
//                dateInit="本周";
//            }else{
            dateInit = Utils.changeWeek(currentTime);
//            }
        } else if ("2".equals(reportType)) {
//            if(currentTime.equals(currentOldTime)){
//                dateInit="本月";
//            }else{
            dateInit = Utils.changeCnDate(currentTime);
//            }
        } else if ("3".equals(reportType)) {
//            if(currentTime.equals(currentOldTime)){
//                dateInit="本日";
//            }else{
            dateInit = Utils.changeCnDate(currentTime);
//            }
        }
        tvComplete.setText(dateInit + "已提交" + reportName + "的员工");
        tvNoComplete.setText(dateInit + "未提交" + reportName + "的员工");
    }

    private void getData() {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("periodName", currentTime);
        map.put("teamCode", teamCode);
        map.put("reportType", reportType);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<LogUserEntity>>>() {
        }.getType(), null, Urls.selectReportDoneEmp, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<LogUserEntity>>() {
            @Override
            public void onSuccess(List<LogUserEntity> data) {
                dismissLoading();
                completeList.clear();
                completeNoList.clear();
                chaYueList.clear();
                if (tvNoComplete == null || completeNoRv == null) {
                    return;
                }
                for (int i = 0; i < data.size(); i++) {
//                    done 0未完成 1已完成 2查阅者
                    if ( "2".equals(data.get(i).getDone())) {
                        LogUserEntity logUserEntity = data.get(i);
                        if (owerEmployeeCode.equals(data.get(i).getEmployee_code())) {
                            logUserEntity.setOwer(true);
                            chaYueList.add(0, logUserEntity);
                        } else {
                            chaYueList.add(logUserEntity);
                        }
                    } else if ("1".equals(data.get(i).getDone())) {
                        LogUserEntity logUserEntity = data.get(i);
                        if (owerEmployeeCode.equals(data.get(i).getEmployee_code())) {
                            logUserEntity.setOwer(true);
                            completeList.add(0, logUserEntity);
                        } else {
                            completeList.add(logUserEntity);
                        }
                    } else {
                        LogUserEntity logUserEntity = data.get(i);
                        if (owerEmployeeCode.equals(data.get(i).getEmployee_code())) {
                            logUserEntity.setOwer(true);
                            completeNoList.add(0, logUserEntity);
                        } else {
                            completeNoList.add(logUserEntity);
                        }
                    }

                }
                if (chaYueList.size() == 0) {
                    tvChaYue.setVisibility(View.GONE);
                    chaYueRv.setVisibility(View.GONE);
                } else {
                    tvChaYue.setVisibility(View.VISIBLE);
                    chaYueRv.setVisibility(View.VISIBLE);
                    chaYueAdapter.notifyDataSetChanged();
                }
                if (completeNoList.size() == 0) {
                    llNoComplete.setVisibility(View.GONE);
                    completeNoRv.setVisibility(View.GONE);
                } else {
                    llNoComplete.setVisibility(View.VISIBLE);
                    completeNoRv.setVisibility(View.VISIBLE);
                    completeNoAdapter.notifyDataSetChanged();
                }
                if (completeList.size() == 0) {
                    tvComplete.setVisibility(View.GONE);
                    completeRv.setVisibility(View.GONE);
                } else {
                    tvComplete.setVisibility(View.VISIBLE);
                    completeRv.setVisibility(View.VISIBLE);
                    completeAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    private void pushReportByWx(String content) {
        //催一下
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("periodName", currentTime);
        map.put("teamCode", teamCode);
        map.put("teamName", teamName);
        map.put("reportType", reportType);
        map.put("remark", content);
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.pushReportByWx, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {

                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        dismissLoading();
                        numRush++;
                        oldTime = System.currentTimeMillis();
                        new ShareUtils().putString(LogManagerCompleteActivity.this, teamCode, currentDate + "_" + System.currentTimeMillis() + "_" + numRush);
                        tvHurry.setText("催一下(" + numRush + "/2)");
                        MyToast.show("已经催过了，请稍后查看");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.tvHurry, R.id.common_right_iv_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvHurry:
                if (numRush >= 2) {
                    MyToast.show("每日可以发送2次提醒，今日已达上限");
                } else {
                    if (!timeEnd || (System.currentTimeMillis() - oldTime) < 3600 * 1000) {
                        MyToast.show("1小时内只能发送1次提醒");
                        return;
                    }
                    new LogHurryDialog(this, reportName, numRush, new LogHurryDialogListener() {
                        @Override
                        public void onClick(String content) {
                            pushReportByWx(content);
                        }
                    }).show();
                }
                break;
            case R.id.common_right_iv_ll:
                if ("2".equals(reportType)) {
                    showDatePickDialog(2);
                } else if ("1".equals(reportType)) {
                    if (commonTitleTxt == null) {
                        return;
                    }
                    if (timeInt == 6) {
                        allList.clear();
                        allList.addAll(oldAllList);
                        yearList.clear();
                        yearList.addAll(oldYearList);
                        new WeekDialog(LogManagerCompleteActivity.this, yearChoice, weekChoice, yearList, allList, new WeekDialogListener() {
                            @Override
                            public void onClick(String yearIndex, String weekIndex) {
                                for (int i = 0; i < 6; i++) {
                                    if (oldYearList.get(i).equals(yearIndex)) {
                                        for (int j = 0; j < oldAllList.get(i).size(); j++) {
                                            if (oldAllList.get(i).get(j).equals(weekIndex)) {
                                                yearChoice = i;
                                                weekChoice = j;
                                                currentTime = yearIndex.substring(0, 4) + "-" + weekIndex.split("至")[1].substring(0, 5);
                                                commonTitleTxt.setText(Utils.changeWeek(currentTime));
                                                initDate();
                                                getData();
                                            }
                                        }
                                    }
                                }
                            }
                        }).show();

                    } else {
                        showDatePickDialog(0);
                    }

                } else {
                    showDatePickDialog(0);
                }
                break;
        }
    }

    private int timeInt = 0;
    private List<List<WeekEntity>> weekEntityList = new ArrayList<>();
    private List<List<String>> allList = new ArrayList<>();
    private List<List<String>> oldAllList = new ArrayList<>();
    private List<String> yearList = new ArrayList<>();
    private List<String> oldYearList = new ArrayList<>();
    private int yearChoice = 4, weekChoice;//选择周的时候专用字段

    private void getWeek() {
        int year = Calendar.getInstance().get(Calendar.YEAR);
        yearList.add((year - 4) + "年");
        oldYearList.add((year - 4) + "年");
        yearList.add((year - 3) + "年");
        oldYearList.add((year - 3) + "年");
        yearList.add((year - 2) + "年");
        oldYearList.add((year - 2) + "年");
        yearList.add((year - 1) + "年");
        oldYearList.add((year - 1) + "年");
        yearList.add(year + "年");
        oldYearList.add(year + "年");
        yearList.add((year + 1) + "年");
        oldYearList.add((year + 1) + "年");
        weekChoice = Utils.getCurrentWeek(currentTime) - 1;
        if (weekChoice == 0 && 11 == Calendar.getInstance().get(Calendar.MONTH)) {
            yearChoice = yearChoice + 1;
        }
        for (int i = 0; i < yearList.size(); i++) {
            if (yearList.get(i).substring(0, 4).equals(currentTime.substring(0, 4))) {
                yearChoice = i;
            }
            List<String> list = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            List<WeekEntity> weekEntities = new ArrayList<>();
            allList.add(list);
            oldAllList.add(list2);
            weekEntityList.add(weekEntities);
        }
        for (int i = 0; i < yearList.size(); i++) {
            int y = i;
            Map<String, String> map = new HashMap<>();
            map.put("year", yearList.get(i).substring(0, 4));
            MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WeekEntity>>>() {
            }.getType(), null, Urls.selectWeekByYear, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WeekEntity>>() {
                @Override
                public void onSuccess(List<WeekEntity> data) {
                    timeInt++;
                    for (int j = 0; j < data.size(); j++) {
                        allList.get(y).add("第" + data.get(j).getWeekNum() + "周(" + data.get(j).getStartTime().substring(5, 10) + "至" + data.get(j).getEndTime().substring(5, 10) + ")");
                        oldAllList.get(y).add("第" + data.get(j).getWeekNum() + "周(" + data.get(j).getStartTime().substring(5, 10) + "至" + data.get(j).getEndTime().substring(5, 10) + ")");
                    }
                    weekEntityList.get(y).addAll(data);
                }

                @Override
                public void onError(String errorMsg) {
                }
            });
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;
    String monthS = "", dayS = "";

    private void showDatePickDialog(int state) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mYear == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        if (commonTitleTxt == null) {
            return;
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        mDay = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS = dayOfMonth + "";
                        } else {
                            dayS = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS = month + "";
                        } else {
                            monthS = "0" + month;
                        }
                        if ("2".equals(reportType)) {
                            currentTime = year + "-" + monthS;
                        } else {
                            currentTime = year + "-" + monthS + "-" + dayS;
                        }
                        if ("1".equals(reportType)) {
                            commonTitleTxt.setText(Utils.changeWeek(currentTime));
                        } else {
                            commonTitleTxt.setText(Utils.changeCnDate(currentTime));
                        }
                        initDate();
                        getData();
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(state);
    }

    class MyContactEntityAdapter extends BaseQuickAdapter<LogUserEntity, BaseViewHolder> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context, @Nullable List<LogUserEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, LogUserEntity item) {

            RelativeLayout rlInit = helper.getView(R.id.rlInit);
            RelativeLayout rlRl = helper.getView(R.id.rlRl);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvGuan = helper.getView(R.id.tvGuan);
            TextView tvYue = helper.getView(R.id.tvYue);
            ImageView ivInit = helper.getView(R.id.ivInit);
            ImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivType = helper.getView(R.id.ivType);
            ivType.setVisibility(View.GONE);
            if (item.isOwer()) {
                rlInit.setVisibility(View.GONE);
                rlRl.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(LogManagerCompleteActivity.this, item.getHead_photo_thumb_url(), ivHead, R.drawable.default_user_head, 8);
                tvName.setText(item.getEmployee_name());
                tvName.setVisibility(View.VISIBLE);
                tvGuan.setVisibility(View.VISIBLE);
                if ("2".equals(item.getDone())) {
                    tvYue.setVisibility(View.VISIBLE);
                } else {
                    tvYue.setVisibility(View.GONE);
                }
            } else {
                //普通人
                rlInit.setVisibility(View.GONE);
                rlRl.setVisibility(View.VISIBLE);
                tvGuan.setVisibility(View.GONE);
                GlideUtils.loadCustomRound(LogManagerCompleteActivity.this, item.getHead_photo_thumb_url(), ivHead, R.drawable.default_user_head, 8);
                tvName.setText(item.getEmployee_name());
                if ("2".equals(item.getDone())) {
                    tvYue.setVisibility(View.VISIBLE);
                } else {
                    tvYue.setVisibility(View.GONE);
                }
                tvName.setVisibility(View.VISIBLE);

            }
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isNull(item.getEmployee_code())) {
                        return;
                    }
                    Intent intent = new Intent(LogManagerCompleteActivity.this, LogDateCompleteActivity.class);
                    intent.putExtra("employeeCode", item.getEmployee_code());
                    intent.putExtra("teamCode", teamCode);
                    intent.putExtra("reportType", reportType);
                    startActivity(intent);
                }
            });
        }

    }

}
